# import requests
# import json

# DIFY_APP_Key = 'app-JqYy5uTZLr4oZDDJ44G8tFJo'

# url = 'https://api.dify.ai/v1/chat-messages'
# headers = {
#     'Authorization': f'Bearer {DIFY_APP_Key}',
#     'Content-Type': 'application/json'
# }

# data = {
#     "inputs": {},
#     "query": "What are the specs of the iPhone 13 Pro Max?",
#     "response_mode": "streaming",
#     "conversation_id": "",
#     "user": "abc-123",
#     "files": [
#         {
#             "type": "image",
#             "transfer_method": "remote_url",
#             "url": "https://cloud.dify.ai/logo/logo-site.png"
#         }
#     ]
# }

# response = requests.post(url, headers=headers, json=data)

# # 打印响应内容
# print(response.text)

import aiohttp
import asyncio
import json
import logging

# DIFY_APP_Key = 'app-JqYy5uTZLr4oZDDJ44G8tFJo'

DIFY_APP_Key = 'app-C4grvu7LnMxANo04ybipNShP'

async def ask_dify(question):
    logging.info("调用ask_dify提问")
    answer = ''  # 初始化答案字符串

    url = 'https://api.dify.ai/v1/chat-messages'
    headers = {
        'Authorization': f'Bearer {DIFY_APP_Key}',
        'Content-Type': 'application/json'
    }
    
    data = {
        "inputs": {},
        "query": question,
        "response_mode": "streaming",
        "conversation_id": "",
        "user": "abc-123",
        "files": [
            {
                "type": "image",
                "transfer_method": "remote_url",
                "url": "https://cloud.dify.ai/logo/logo-site.png"
            }
        ]
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, json=data) as response:
            async for chunk in response.content.iter_chunked(1024):
                
                # 将接收到的chunk解码为字符串
                chunk_str = chunk.decode('utf-8')
                
                # 检查是否以 'data:' 开头
                if chunk_str.strip().startswith('data:'):
                    # 提取JSON字符串
                    json_str = chunk_str.strip()[5:].strip()  # 去除 'data:' 和可能的空白字符
                    
                    try:
                        # 解析JSON数据
                        json_data = json.loads(json_str)
                        # 提取answer字段
                        answer_chunk = json_data.get('answer', '')
                        if answer_chunk:
                            # 遍历chunk中的每个字符
                            for char in answer_chunk:
                                answer += char  # 将字符加到回答中
                                # 如果当前字符是标点符号，检查是否可以发送回答
                                if char[-1] in ["。", "！", "？", "!", "?", ",", ".", ";"]:
                                    logging.info(f"发送回答: {answer}")
                                    yield answer  # 发送当前累积的回答
                                    answer = ''  # 重置回答字符串，以便拼接下一个回答
                    except json.JSONDecodeError as e:
                        logging.error(f"Error decoding JSON: {e}")

async def main():
    question = "What are the specs of the iPhone 13 Pro Max?"
    async for answer in ask_dify(question):
        print('流式回答如下：')
        print(answer)

if __name__ == "__main__":
    asyncio.run(main())